package com.haoze.nurseapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.dto.CronDescriber;
import com.haoze.common.enumeration.ConstantEnum;
import com.haoze.common.enumeration.StateEnum;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.*;
import com.haoze.nurseapp.aop.NurseLogAop;
import com.haoze.nurseapp.dao.MealListMapper;
import com.haoze.nurseapp.dao.OrderMapper;
import com.haoze.nurseapp.dao.PatientInHospitalMapper;
import com.haoze.nurseapp.dao.UserMapper;
import com.haoze.nurseapp.dto.*;
import com.haoze.nurseapp.dto.order.OrderListAppDto;
import com.haoze.nurseapp.enumeration.OrderExecStatusEnum;
import com.haoze.nurseapp.enumeration.OrderQueryStatusTypeEnum;
import com.haoze.nurseapp.enumeration.OrderTypeEnum;
import com.haoze.nurseapp.model.*;
import com.haoze.nurseapp.service.OrderService;
import com.haoze.nurseapp.service.feign.NurseService;
import com.haoze.nurseapp.vo.OrderDetailByOrderNoVo;
import com.haoze.nurseapp.vo.OrderInfoByInpatNoVo;
import com.haoze.nurseapp.vo.OrderRevieInfoDetailByInpatVo;
import com.haoze.nurseapp.vo.OrderReviewInfoByInpatVo;
import com.haoze.nurseapp.vo.order.OrderTaskInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.kafka.common.utils.CopyOnWriteMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

import static org.apache.commons.lang3.time.DateUtils.truncate;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    OrderMapper orderMapper;
    @Autowired
    PatientInHospitalMapper patientInHospitalMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private NurseService nurseService;

    @Value("${his.url.circulation2}")
    private String circulationUrl2;

    @Value("${his.url.query}")
    private String hisQueryUrl;

    //@Value("${his.url.circulation2}")
    private Boolean switchFlag=false;

    @Autowired
    private MealListMapper mealListMapper;

    @Value("${his.url.circulation}")
    private String circulationUrl;


    private static final Logger log = LoggerFactory.getLogger(NurseLogAop.class);



    @Override
    public Result orderType() {
        return ResultGenerator.genOkResult(orderMapper.selectOrderType());
    }

    @Override
    public Result orderDetail(String inpatorderdataId, String startDate, String endDate, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        PageInfo<OrderDetailByOrderNoVo> pageInfo = new PageInfo<>(orderMapper.selectOrderDetail(inpatorderdataId, startDate, endDate));
        return ResultGenerator.genOkResult(pageInfo);
    }

    @Override
    public Result orderInfoByOrderDataId(String inpatorderdataId) {
        OrderInfoByInpatNoVo orderVo = orderMapper.queryOrder(inpatorderdataId);
        formatOrderVo(orderVo);
        return ResultGenerator.genOkResult(orderVo);
    }

    @Override
    public PageInfo<OrderInfoByInpatNoVo>  queryPagesList(OrderPageDto pageDto) {
        List<OrderInfoByInpatNoVo> ordersList = this.orderMapper.queryOrderList1(pageDto);

        List<OrderInfoByInpatNoVo> resultList = new ArrayList<>();
        int totalLength = 0;
        //分组
        if(!CollectionUtils.isEmpty(ordersList)){
            Map<String, List<OrderInfoByInpatNoVo>> collect = ordersList.stream().collect(Collectors.groupingBy(e -> fetchOrderGroupKey(e)));
            if(collect!=null) {
                for (String key : collect.keySet()) {
                    String inpatNum = key.split("#")[0];
                    String orderNo = key.split("#")[1];
                    if(!CollectionUtils.isEmpty(collect.get(key)) && collect.get(key).size()>=1){
                        OrderInfoByInpatNoVo orderInfoByInpatNoVo = collect.get(key).get(0);
                        orderInfoByInpatNoVo.setType(orderInfoByInpatNoVo.getType().substring(0, 2));
                        this.setValue(orderInfoByInpatNoVo);
                        List<OrderInfoByInpatNoVo> orderInfoByInpatNoVoList = new ArrayList<>();
                        for (OrderInfoByInpatNoVo orderInfo : collect.get(key)) {
                            OrderInfoByInpatNoVo newOrderInfoByInpatNoVo= new OrderInfoByInpatNoVo();
                            BeanUtils.copyProperties(orderInfo,newOrderInfoByInpatNoVo);
                            orderInfoByInpatNoVoList.add(newOrderInfoByInpatNoVo);
                        }
                        orderInfoByInpatNoVo.setOrderInfoByInpatNoVoList(orderInfoByInpatNoVoList);
                        resultList.add(orderInfoByInpatNoVo);
                    }
                }
                resultList = resultList.stream().sorted(Comparator.comparing(OrderInfoByInpatNoVo::getOrderType).thenComparing(OrderInfoByInpatNoVo::getPlanBeginDatetime).thenComparingInt(OrderInfoByInpatNoVo::getSort)
                        .thenComparing(OrderInfoByInpatNoVo::getAdministration, Comparator.nullsLast(String::compareTo))
                        .thenComparing(OrderInfoByInpatNoVo::getOrdersItem))
                        .collect(Collectors.toList());
            }
            totalLength = resultList.size();

            if (pageDto.getPageNum() != 0 && pageDto.getPageSize() != 0) {
                resultList = resultList.stream().skip((pageDto.getPageNum() - 1) * pageDto.getPageSize()).limit(pageDto.getPageSize()).collect(Collectors.toList());
            }
        }
        PageInfo<OrderInfoByInpatNoVo> pageInfo = new PageInfo<>(resultList);
        pageInfo.setTotal(totalLength);
        return pageInfo;
    }
    public void setValue(OrderInfoByInpatNoVo orderInfoByInpatNoVo){
        //临时医嘱
        if(orderInfoByInpatNoVo.getOrderStatusValue()!=null && orderInfoByInpatNoVo.getOrderStatusValue()==0) {
            if (orderInfoByInpatNoVo.getType().equals("药品")) {
                String hisExecDateTime = orderInfoByInpatNoVo.getExecDatetime();
                String hisExecUserName = orderInfoByInpatNoVo.getExecUserName();
                orderInfoByInpatNoVo.setExecDatetime(null);
                orderInfoByInpatNoVo.setExecUserName(null);
                if("雾化单".equals(orderInfoByInpatNoVo.getAdministrationType())){
                    Map<String, String> map = orderMapper.selectAtomizationTime(orderInfoByInpatNoVo.getInpatorderdataId(),null);
                    if(map!=null) {
                        orderInfoByInpatNoVo.setExecDatetime(map.get("atomizationTime"));
                        orderInfoByInpatNoVo.setExecUserName(map.get("atomizationTimeUser"));
                    }
                }else if("注射单".equals(orderInfoByInpatNoVo.getAdministrationType())){
                    if("皮内注射".equals(orderInfoByInpatNoVo.getAdministration()) || "皮试".equals(orderInfoByInpatNoVo.getAdministration())){
                        Map<String, String> map = orderMapper.selectInjectionTime1(orderInfoByInpatNoVo.getInpatorderdataId(),null);
                        if(map!=null) {
                            orderInfoByInpatNoVo.setExecDatetime(map.get("injectionTime1"));
                            orderInfoByInpatNoVo.setExecUserName(map.get("injectionTimeUser1"));
                        }
                    }else if("皮下注射".equals(orderInfoByInpatNoVo.getAdministration()) || "皮下注射(胰岛素)".equals(orderInfoByInpatNoVo.getAdministration())|| "M".equals(orderInfoByInpatNoVo.getAdministration())){
                        Map<String, String> map = orderMapper.selectInjectionTime2(orderInfoByInpatNoVo.getInpatorderdataId(),null);
                        if(map!=null) {
                            orderInfoByInpatNoVo.setExecDatetime(map.get("injectionTime2"));
                            orderInfoByInpatNoVo.setExecUserName(map.get("injectionTimeUser2"));
                        }
                    }else{
                        Map<String, String> map = orderMapper.selectInfusionTime(orderInfoByInpatNoVo.getInpatorderdataId(),null);
                        if(map!=null) {
                            orderInfoByInpatNoVo.setExecDatetime(map.get("infusionTime"));
                            orderInfoByInpatNoVo.setExecUserName(map.get("infusionTimeUser"));
                        }
                    }
                }else if("输液单".equals(orderInfoByInpatNoVo.getAdministrationType())){
                    Map<String, String> map = orderMapper.selectInfusionTime(orderInfoByInpatNoVo.getInpatorderdataId(),null);
                    if(map!=null) {
                        orderInfoByInpatNoVo.setExecDatetime(map.get("infusionTime"));
                        orderInfoByInpatNoVo.setExecUserName(map.get("infusionTimeUser"));
                    }
                }else if("服药单".equals(orderInfoByInpatNoVo.getAdministrationType())){
                    Map<String, String> map = orderMapper.selectTakeTime(orderInfoByInpatNoVo.getInpatorderdataId());
                    if(map!=null) {
                        orderInfoByInpatNoVo.setExecDatetime(map.get("takeTime"));
                        orderInfoByInpatNoVo.setExecUserName(map.get("takeTimeUser"));
                    }

                }else if("肠内营养".equals(orderInfoByInpatNoVo.getAdministrationType())){
                    Map<String, String> map = orderMapper.selectNutritionTime(orderInfoByInpatNoVo.getInpatorderdataId(),null);
                    if(map!=null) {
                        orderInfoByInpatNoVo.setExecDatetime(map.get("nutritionTime"));
                        orderInfoByInpatNoVo.setExecUserName(map.get("nutritionTimeUser"));
                    }
                } else if("治疗单".equals(orderInfoByInpatNoVo.getAdministrationType()) || "其他给药单".equals(orderInfoByInpatNoVo.getAdministrationType())){
                    orderInfoByInpatNoVo.setExecDatetime(hisExecDateTime);
                    orderInfoByInpatNoVo.setExecUserName(hisExecUserName);
                }
            }else if (orderInfoByInpatNoVo.getType().equals("输血")) {
                Map<String, String> map = orderMapper.selectBloodTime(orderInfoByInpatNoVo.getInpatorderdataId());
                if(map!=null) {
                    orderInfoByInpatNoVo.setExecDatetime(map.get("bloodTime"));
                    orderInfoByInpatNoVo.setExecUserName(map.get("bloodTimeUser"));
                }else{
                    orderInfoByInpatNoVo.setExecDatetime(null);
                    orderInfoByInpatNoVo.setExecUserName(null);
                }
            } else if (orderInfoByInpatNoVo.getType().equals("检疗") && orderInfoByInpatNoVo.getOrdersItem().equals("检验")) {
                orderInfoByInpatNoVo.setExecDatetime(orderInfoByInpatNoVo.getBloodTime());
                orderInfoByInpatNoVo.setExecUserName(orderInfoByInpatNoVo.getBloodTimeUser());
            } else if (orderInfoByInpatNoVo.getType().equals("检疗") && orderInfoByInpatNoVo.getOrdersItem().equals("转科")) {
                orderInfoByInpatNoVo.setExecDatetime(orderInfoByInpatNoVo.getDeptOutTime());
                orderInfoByInpatNoVo.setExecUserName(orderInfoByInpatNoVo.getDeptOutTimeUser());
            } else if (orderInfoByInpatNoVo.getType().equals("检疗") && orderInfoByInpatNoVo.getOrdersItem().equals("换床")) {
                orderInfoByInpatNoVo.setExecDatetime(orderInfoByInpatNoVo.getBedOutTime());
                orderInfoByInpatNoVo.setExecUserName(orderInfoByInpatNoVo.getBedOutTimeUser());
            }else if ("碘试验(病房)".equals(orderInfoByInpatNoVo.getOrderItemss()) || "碘试验(注射室)".equals(orderInfoByInpatNoVo.getOrderItemss())){
                Map<String, String> map = orderMapper.selectInjectionTime3(orderInfoByInpatNoVo.getInpatorderdataId(),null);
                if(map!=null) {
                    orderInfoByInpatNoVo.setExecDatetime(map.get("injectionTime3"));
                    orderInfoByInpatNoVo.setExecUserName(map.get("injectionTimeUser3"));
                }else{
                    orderInfoByInpatNoVo.setExecDatetime(null);
                    orderInfoByInpatNoVo.setExecUserName(null);
                }
            }else if ("胰岛素泵持续皮下注射胰岛素".equals(orderInfoByInpatNoVo.getOrderItemss())){
                Map<String, String> map = orderMapper.selectInjectionTime4(orderInfoByInpatNoVo.getInpatorderdataId(),null);
                if(map!=null) {
                    orderInfoByInpatNoVo.setExecDatetime(map.get("injectionTime4"));
                    orderInfoByInpatNoVo.setExecUserName(map.get("injectionTimeUser4"));
                }else{
                    orderInfoByInpatNoVo.setExecDatetime(null);
                    orderInfoByInpatNoVo.setExecUserName(null);
                }
            }else if("检验".equals(orderInfoByInpatNoVo.getType())) {
                orderInfoByInpatNoVo.setExecDatetime(orderInfoByInpatNoVo.getCollectionTime());
                orderInfoByInpatNoVo.setExecUserName(orderInfoByInpatNoVo.getCollectionTimeUser());
            }else{
                orderInfoByInpatNoVo.setExecDatetime(orderInfoByInpatNoVo.getExecDatetime());
                orderInfoByInpatNoVo.setExecUserName(orderInfoByInpatNoVo.getExecUserName());
            }
            if(StringUtils.isNotBlank(orderInfoByInpatNoVo.getSignNurse())){
                orderInfoByInpatNoVo.setExecUserName(orderInfoByInpatNoVo.getSignNurse());
            }
            if(StringUtils.isNotBlank(orderInfoByInpatNoVo.getSignNurseDatetime())){
                orderInfoByInpatNoVo.setExecDatetime(orderInfoByInpatNoVo.getSignNurseDatetime());
            }

            if (StringUtils.isNotBlank(orderInfoByInpatNoVo.getStopExecutionDate()) && orderInfoByInpatNoVo.getStopExecutionDate().length() >= 16) {
                orderInfoByInpatNoVo.setStopExecutionDate(orderInfoByInpatNoVo.getStopExecutionDate().substring(0, 16));
            }
            if (StringUtils.isNotBlank(orderInfoByInpatNoVo.getExecDatetime()) && orderInfoByInpatNoVo.getExecDatetime().length() >= 16) {
                orderInfoByInpatNoVo.setExecDatetime(orderInfoByInpatNoVo.getExecDatetime().substring(0, 16));
            }
        }
    }


    private static String fetchOrderGroupKey(OrderInfoByInpatNoVo orderInfoByInpatNoVo){
        return orderInfoByInpatNoVo.getInpatNum()+"#"+orderInfoByInpatNoVo.getOrderNo();
    }

    @Override
    public Result reviewList(String inpatList, String startDatetime, String endDateTime,String type,String bedNo) {

        if(StringUtils.isNotBlank(inpatList)){
            if("0".equals(type)){
                //未复核
                List<OrderReviewInfoByInpatVo> list = orderMapper.reviewList(inpatList.split(","), startDatetime, endDateTime, switchFlag,bedNo);
                if(!CollectionUtils.isEmpty(list)){
                    list.stream().forEach(orderReviewInfoByInpatVo->{
                        List<OrderRevieInfoDetailByInpatVo> children = orderReviewInfoByInpatVo.getChildren();
                        if(!CollectionUtils.isEmpty(children)){
                            children.stream().forEach(map->{
                                if("stop".equals(map.getFlag())){
                                    List<OrderOperationLogDTO> logList = orderMapper.queryUpdateStopDateLogByInpatorderdataId(map.getInpatorderdataId());
                                    if(!CollectionUtils.isEmpty(logList)) {
                                        //8 停止日志
                                        List<OrderOperationLogDTO> log2 = logList.stream().filter(s -> "8".equals(s.getOperationType())).collect(Collectors.toList());
                                        //7 停止复核成功
                                        List<OrderOperationLogDTO> log1 = logList.stream().filter(s -> "7".equals(s.getOperationType())).collect(Collectors.toList());
                                        if ((!CollectionUtils.isEmpty(log2) && log2.size() >= 2) || (!CollectionUtils.isEmpty(log1) && log1.size() >= 2)) {
                                            if(!CollectionUtils.isEmpty(log1)){
                                                List<String> stopDateTimeList = log1.stream().map(s -> s.getStopDateTime()).collect(Collectors.toList());
                                                map.setPreStopTimeRange(StringUtils.join(stopDateTimeList, ","));
                                            }
                                        }
                                    }
                                }
                                //获取执行时间
                                if (StringUtils.isNotEmpty(map.getCronDescriber())) {
                                    String hisExecTime = CronUtil.hisConverter(JSONObject.parseObject(map.getCronDescriber(), CronDescriber.class));
                                    map.setFreqTimes(hisExecTime);
                                }
                            });
                            orderReviewInfoByInpatVo.setChildren(children.stream().sorted(Comparator.comparing(OrderRevieInfoDetailByInpatVo::getOrderType).thenComparing(OrderRevieInfoDetailByInpatVo::getPlanBeginDatetime).thenComparingInt(OrderRevieInfoDetailByInpatVo::getSort).thenComparing(OrderRevieInfoDetailByInpatVo::getAdministration, Comparator.nullsLast(String::compareTo))
                                    .thenComparing(OrderRevieInfoDetailByInpatVo::getOrderNo).thenComparing(OrderRevieInfoDetailByInpatVo::getOrderSubNo).thenComparing(OrderRevieInfoDetailByInpatVo::getOrdersItem))
                                        .collect(Collectors.toList()));
                        }
                    });
                }
                return ResultGenerator.genOkResult(list);
            }else if("1".equals(type)){
                //已复核
                List<OrderReviewInfoByInpatVo> list = orderMapper.reviewedList(inpatList.split(","), startDatetime, endDateTime,bedNo);
                if(!CollectionUtils.isEmpty(list)){
                    list.stream().forEach(orderReviewInfoByInpatVo->{
                        List<OrderRevieInfoDetailByInpatVo> children = orderReviewInfoByInpatVo.getChildren();
                        List<OrderRevieInfoDetailByInpatVo> childrenTemp = new ArrayList<>();

                        if(!CollectionUtils.isEmpty(children)){
                            children.stream().forEach(map->{
                                //获取执行时间
                                if (StringUtils.isNotEmpty(map.getCronDescriber())) {
                                    String hisExecTime = CronUtil.hisConverter(JSONObject.parseObject(map.getCronDescriber(), CronDescriber.class));
                                    map.setFreqTimes(hisExecTime);
                                }
                                String orderType = map.getOrderType();
                                String endTime = map.getEndDateTime();
                                String execStatusHis = map.getExecStatusHis();

                                if(StringUtils.isNotBlank(startDatetime) && StringUtils.isNotBlank(endDateTime) && StringUtils.isNotBlank(map.getCreateDatetime())
                                        && endDateTime.compareTo(map.getCreateDatetime().substring(0,10))>=0 && map.getCreateDatetime().substring(0,10).compareTo(startDatetime)>=0){
                                    childrenTemp.add(map);
                                }else if(StringUtils.isBlank(startDatetime) && StringUtils.isBlank(endDateTime)){
                                    childrenTemp.add(map);
                                }
                                //长期医嘱并且exec_status_his=3,结束时间不为空
                                if(StringUtils.isNotBlank(orderType) && "1".equals(orderType) && StringUtils.isNotBlank(endTime) && StringUtils.isNotBlank(execStatusHis) && "3".equals(execStatusHis)){
                                    OrderRevieInfoDetailByInpatVo stopMap = new OrderRevieInfoDetailByInpatVo();
                                    BeanUtils.copyProperties(map,stopMap);
                                    stopMap.setPlanBeginDatetime(endTime);
                                    stopMap.setOrdersItem("停 "+stopMap.getOrdersItem());
                                    stopMap.setCreateDatetime(StringUtils.isNotBlank(stopMap.getStopDatetime())?stopMap.getStopDatetime():endTime);
                                    stopMap.setCreateTime(StringUtils.isNotBlank(stopMap.getStopTime())?stopMap.getStopTime():stopMap.getEndTime());
                                    stopMap.setOrderNo(stopMap.getOrderNo()+".1");
                                    stopMap.setPersonName(stopMap.getStopPersonName());

                                    List<OrderOperationLogDTO> logList = orderMapper.queryUpdateStopDateLogByInpatorderdataId(stopMap.getInpatorderdataId());
                                    if(!CollectionUtils.isEmpty(logList)) {
                                        //8 停止日志
                                        List<OrderOperationLogDTO> log2 = logList.stream().filter(s -> "8".equals(s.getOperationType())).collect(Collectors.toList());
                                        //7 停止复核成功
                                        List<OrderOperationLogDTO> log1 = logList.stream().filter(s -> "7".equals(s.getOperationType())).collect(Collectors.toList());
                                        if ((!CollectionUtils.isEmpty(log2) && log2.size() >= 2) || (!CollectionUtils.isEmpty(log1) && log1.size() >= 2)) {
                                            if(!CollectionUtils.isEmpty(log1)){
                                                List<String> stopDateTimeList = log1.stream().map(s -> s.getStopDateTime()).limit(log1.size()-1).collect(Collectors.toList());
                                                if(!CollectionUtils.isEmpty(stopDateTimeList)) {
                                                    stopMap.setPreStopTimeRange(StringUtils.join(stopDateTimeList, ","));
                                                }
                                            }
                                        }
                                    }

                                    if(StringUtils.isNotBlank(startDatetime) && StringUtils.isNotBlank(endDateTime) && StringUtils.isNotBlank(stopMap.getCreateDatetime())
                                            && endDateTime.compareTo(stopMap.getCreateDatetime().substring(0,10))>=0 && stopMap.getCreateDatetime().substring(0,10).compareTo(startDatetime)>=0){
                                        childrenTemp.add(stopMap);
                                    }else if(StringUtils.isBlank(startDatetime) && StringUtils.isBlank(endDateTime)){
                                        childrenTemp.add(stopMap);
                                    }
                                }
                            });
                            List<OrderRevieInfoDetailByInpatVo> collect = new ArrayList<>();
                            if(!CollectionUtils.isEmpty(childrenTemp)){
                                collect = childrenTemp.stream().sorted(Comparator.comparing(OrderRevieInfoDetailByInpatVo::getOrderType).thenComparing(OrderRevieInfoDetailByInpatVo::getPlanBeginDatetime)
                                        .thenComparingInt(OrderRevieInfoDetailByInpatVo::getSort)
                                        .thenComparing(OrderRevieInfoDetailByInpatVo::getAdministration, Comparator.nullsLast(String::compareTo))
                                        .thenComparing(OrderRevieInfoDetailByInpatVo::getOrderNo)
                                        .thenComparing(OrderRevieInfoDetailByInpatVo::getOrderSubNo)
                                        .thenComparing(OrderRevieInfoDetailByInpatVo::getOrdersItem))
                                        .collect(Collectors.toList());
                            }
                            orderReviewInfoByInpatVo.setChildren(collect);
                        }
                    });

                    //判断
                    List<OrderReviewInfoByInpatVo> listCopy = new ArrayList<>();
                    list.stream().forEach(orderReviewInfoByInpatVo->{
                        if(!CollectionUtils.isEmpty(orderReviewInfoByInpatVo.getChildren())){
                            listCopy.add(orderReviewInfoByInpatVo);
                        }
                    });

                    return ResultGenerator.genOkResult(listCopy);
                }
            }
        }
        return ResultGenerator.genOkResult();
    }


    /**
     * 复核列表
     * @param inpatList
     * @param startDatetime
     * @param endDateTime
     * @return
     */
    public Result queryPatientBedNoList(String wardDeptId,String inpatList, String startDatetime, String endDateTime,String type,String status){
        if("0".equals(type)){
            return ResultGenerator.genOkResult(orderMapper.queryPatientBedNoReviewList(wardDeptId,inpatList,switchFlag,status));
        }else if("1".equals(type)){
            return ResultGenerator.genOkResult(orderMapper.queryPatientBedNoReviewedList(wardDeptId,inpatList,startDatetime,endDateTime,switchFlag,status));
        }
        return ResultGenerator.genOkResult();
    }


    public boolean verifyPassword(final String rawPassword, final String encodedPassword) {
        return this.passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 医嘱复核
     * @param nurseOrdersReviewDTO
     * @return
     */
    //public Result patientOrdersReview(List<OrdersReviewDTO> inpatorderdataIdList){
    @Transactional(rollbackFor = Exception.class)
    public Result patientOrdersReview(NurseOrdersReviewDTO nurseOrdersReviewDTO){
        //inpatorderdataIdList
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        String loginName = nurseOrdersReviewDTO.getLoginName();
        String userPwd = nurseOrdersReviewDTO.getUserPwd();
        String currentWardDeptId = nurseOrdersReviewDTO.getWardDeptId();
        List<OrdersReviewDTO> inpatorderdataIdList = nurseOrdersReviewDTO.getInpatorderdataIds();
        if(!CollectionUtils.isEmpty(inpatorderdataIdList)){
            for(OrdersReviewDTO ordersReviewDTO:inpatorderdataIdList){
                String inpatorderdataId = ordersReviewDTO.getInpatorderdataId();
                String performResult = ordersReviewDTO.getPreformResult();
                //如果EXEC_STATUS_HIS为空
                PatientOrdersDTO patientOrdersEntity = orderMapper.queryPatientOrdersById(inpatorderdataId);
                if(patientOrdersEntity!=null){
                    if(("4".equals(patientOrdersEntity.getExecStatus()) || "9".equals(patientOrdersEntity.getExecStatus()))
                        || "4".equals(patientOrdersEntity.getExecStatusHis())){
                        return ResultGenerator.genFailedResult(patientOrdersEntity.getOrdersItem()+"医嘱已作废,请刷新页面");
                    }
                    //判断皮试结果  1需要皮试结果才能复核
                    if(StringUtils.isNotBlank(patientOrdersEntity.getTestDrugFlag())
                            && "1".equals(patientOrdersEntity.getTestDrugFlag())
                            && !"(-)".equals(performResult)){
                        return ResultGenerator.genFailedResult(patientOrdersEntity.getOrdersItem()+"药品皮试结果未选择或不能为阳性!");
                    }
                    ordersReviewDTO.setPatientOrdersEntity(patientOrdersEntity);
                    ordersReviewDTO.setBedNo(patientOrdersEntity.getBedNo());
                    ordersReviewDTO.setOrderNo(patientOrdersEntity.getOrderNo());
                    ordersReviewDTO.setOrderSubNo(patientOrdersEntity.getOrderSubNo());
                    ordersReviewDTO.setInpatNum(patientOrdersEntity.getInpatNum());
                }
            }
            //验证登录名和密码是否正确
            if (StringUtils.isBlank(loginName)) {
                return ResultGenerator.genFailedResult("账号不能为空");
            }
            if (StringUtils.isBlank(userPwd)) {
                return ResultGenerator.genFailedResult("密码不能为空");
            }
            // 用户名登录
            UserEntity dbUser = userMapper.queryOneUser(loginName);
            if (dbUser == null) {
                return ResultGenerator.genFailedResult("账号["+loginName+"]不存在");
            } else if (StateEnum.EMR_STOP.getValue().equals(dbUser.getLockFlag())) {
                return ResultGenerator.genFailedResult("账号["+loginName+"]被停用");
            } else if (StateEnum.EMR_DEL.getValue().equals(dbUser.getDelFlag())) {
                return ResultGenerator.genFailedResult("账号["+loginName+"]被删除");
            }
            // 验证密码
            if (!verifyPassword(userPwd,dbUser.getUserPwd())) {
                return ResultGenerator.genFailedResult("密码错误");
            }
            //判断登录名是否是该病区的人员
            /*String nurseWardDeptId = orderMapper.queryWardDeptInfoByUserId(dbUser.getUserId());
            if(StringUtils.isBlank(nurseWardDeptId) || !currentWardDeptId.equals(nurseWardDeptId)){
                return ResultGenerator.genFailedResult(loginName+"("+dbUser.getUserName()+")不是"+orderMapper.queryDeptNameByDeptId(currentWardDeptId)+"的病房人员!");
            }*/

            //分组
            Map<String, List<OrdersReviewDTO>> collect = inpatorderdataIdList.stream().collect(Collectors.groupingBy(e -> fetchGroupKey(e)));
            System.out.println(collect);

            Map<String, Object> param = new HashMap<>();
            //param.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
            param.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(dbUser.getUserId()));
            param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm"));
            param.put("ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(currentWardDeptId));
            List<Map<String,Object>> orders = new ArrayList<Map<String,Object>>();
            if(collect!=null){
                for(String key:collect.keySet()){
                    for(OrdersReviewDTO ordersReviewDTO:collect.get(key)){
                        Map<String,Object> orderParam = new HashMap<String,Object>();
                        orderParam.put("primary_id",ordersReviewDTO.getPatientOrdersEntity().getPrimaryId());
                        //皮试结果(-)/(+)
                        orderParam.put("ps_result",ordersReviewDTO.getPreformResult());
                        //新开医嘱复核
                        if((StringUtils.isBlank(ordersReviewDTO.getPatientOrdersEntity().getExecStatusHis()) ||
                                "0".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatusHis()) ||
                                "1".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatusHis()))
                                && (!"4".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatus())
                                && !"3".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatus())
                                && !"9".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatus()))){
                            //是否停止医嘱：1是，0否
                            orderParam.put("start_stop_indicator",0);
                        }else if(StringUtils.isNotBlank(ordersReviewDTO.getPatientOrdersEntity().getExecStatusHis()) &&
                                "2".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatusHis()) &&
                                ordersReviewDTO.getPatientOrdersEntity().getPlanEndDatetime()!=null
                                && (!"4".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatus())
                                && !"3".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatus())
                                && !"9".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatus()))){
                            //是否停止医嘱：1是，0否
                            orderParam.put("start_stop_indicator",1);
                        }
                        orders.add(orderParam);
                    }
                }
            }
            param.put("orders",orders);
            Map<String, Object> requestMap = new HashMap<>();
            Map<String, Object> params = new HashMap<>();
            requestMap.put("request", param);
            params.put("c_request",requestMap);
            //params.put("operationID", ConstantEnum.HIS_ORDERS_REVIEW_10058.getKey());
            params.put("operationID", ConstantEnum.HIS_ORDERS_REVIEW_10058.getKey());
            System.out.println(JSON.toJSONString(params));
            JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, params);
            if(jsonObject.isEmpty()){
                return ResultGenerator.genFailedResult("医嘱复核失败");
            }
            log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
            if (null != jsonObject) {
                Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                if (resInt < 0) {
                    return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                }
            }

            //更新医嘱表
            if(collect!=null){
                List<PatientOrdersEntity> patientOrdersEntityList = new CopyOnWriteArrayList<>();
                List<OrderOperationLogEntity> orderOperationLogEntityList = new CopyOnWriteArrayList<>();
                for(String key:collect.keySet()){
                    Date date = new Date();
                    Timestamp checkTime = new Timestamp(date.getTime());
                    for(OrdersReviewDTO ordersReviewDTO:collect.get(key)){
                        //实例化对象
                        Date startDate=null;
                        Date releaseDate=null;
                        try {
                            if(StringUtils.isNotBlank(ordersReviewDTO.getStartDate()) && ordersReviewDTO.getStartDate().length()>=16){
                                startDate = DateUtils.parseDate(ordersReviewDTO.getStartDate().substring(0,16)+":00","yyyy-MM-dd HH:mm:ss");
                            }
                            if(StringUtils.isNotBlank(ordersReviewDTO.getReleaseDate()) && ordersReviewDTO.getReleaseDate().length()>=16){
                                releaseDate =DateUtils.parseDate(ordersReviewDTO.getReleaseDate().substring(0,16)+":00","yyyy-MM-dd HH:mm:ss");
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        //新开医嘱复核
                        if((StringUtils.isBlank(ordersReviewDTO.getPatientOrdersEntity().getExecStatusHis()) ||
                                "0".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatusHis()) ||
                                "1".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatusHis()))
                                && (!"4".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatus())
                                && !"3".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatus())
                                && !"9".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatus()))){
                            //更新医嘱状态
                            PatientOrdersEntity patientOrdersInfo = new PatientOrdersEntity();
                            patientOrdersInfo.setExecStatusHis("2");
                            patientOrdersInfo.setInpatorderdataId(ordersReviewDTO.getPatientOrdersEntity().getInpatorderdataId());
                            patientOrdersInfo.setPerformResult(ordersReviewDTO.getPreformResult());
                            patientOrdersInfo.setCheckDate(checkTime);
                            //存放person_id
                            patientOrdersInfo.setCheckNursePersonId(dbUser.getPersonId());
                            patientOrdersEntityList.add(patientOrdersInfo);

                            OrderOperationLogEntity orderOperationLogEntity = new OrderOperationLogEntity(UUIDUtil.randomString(),null,ordersReviewDTO.getInpatNum(),null,patientOrdersInfo.getInpatorderdataId(),
                                    date,6,dbUser.getPersonId(),startDate,releaseDate);
                            orderOperationLogEntity.initAdd();
                            orderOperationLogEntityList.add(orderOperationLogEntity);
                            //orderMapper.updatePatientOrderById(patientOrdersInfo);

                        }else if(StringUtils.isNotBlank(ordersReviewDTO.getPatientOrdersEntity().getExecStatusHis()) &&
                                "2".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatusHis()) &&
                                ordersReviewDTO.getPatientOrdersEntity().getPlanEndDatetime()!=null
                                && (!"4".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatus())
                                && !"3".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatus())
                                && !"9".equals(ordersReviewDTO.getPatientOrdersEntity().getExecStatus()))){
                            //更新医嘱状态
                            PatientOrdersEntity patientOrdersInfo = new PatientOrdersEntity();
                            patientOrdersInfo.setExecStatusHis("3");
                            patientOrdersInfo.setInpatorderdataId(ordersReviewDTO.getPatientOrdersEntity().getInpatorderdataId());
                            //存放person_id
                            //patientOrdersInfo.setStopNurseId(userId);
                            patientOrdersInfo.setStopNurseId(dbUser.getPersonId());
                            patientOrdersInfo.setNurseStopDatetime(checkTime);
                            //orderMapper.updatePatientOrderById(patientOrdersInfo);
                            patientOrdersEntityList.add(patientOrdersInfo);
                            OrderOperationLogEntity orderOperationLogEntity = new OrderOperationLogEntity(UUIDUtil.randomString(),null,ordersReviewDTO.getInpatNum(),null,patientOrdersInfo.getInpatorderdataId(),
                                    date,7,dbUser.getPersonId(),startDate,releaseDate);
                            orderOperationLogEntity.initAdd();
                            orderOperationLogEntityList.add(orderOperationLogEntity);
                        }
                    }
                }
                //修改医嘱加日志
                if(!CollectionUtils.isEmpty(patientOrdersEntityList)){
                    orderMapper.updateBatchPatientOrderByIds(patientOrdersEntityList);
                }
                //添加日志
                if(!CollectionUtils.isEmpty(orderOperationLogEntityList)){
                    orderMapper.insertOrderOperationLog(orderOperationLogEntityList);
                }
            }

            return ResultGenerator.genOkResult("复核成功!");
        }else{
            return ResultGenerator.genOkResult();
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public Result patientOrdersReviewDoctor(List<OrdersReviewDTO> ordersReviewDTOList){
        if(!CollectionUtils.isEmpty(ordersReviewDTOList)){
            Date date = new Date();
            Map<String, Object> param = new HashMap<>();
            //param.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
            param.put("operator", patientInHospitalMapper.queryUserIdByPersonId(ordersReviewDTOList.get(0).getPersonId()));
            param.put("operationdate", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm"));
            param.put("ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(ordersReviewDTOList.get(0).getWardDeptId()));
            List<Map<String,Object>> orders = new ArrayList<Map<String,Object>>();
            for(OrdersReviewDTO ordersReviewDTO:ordersReviewDTOList){
                Map<String,Object> orderParam = new HashMap<String,Object>();
                orderParam.put("primary_id",ordersReviewDTO.getPrimaryId());
                //皮试结果(-)/(+)
                orderParam.put("ps_result","");
                //新开医嘱复核
                //是否停止医嘱：1是，0否
                orderParam.put("start_stop_indicator",0);
                orders.add(orderParam);
            }
            param.put("orders",orders);
            Map<String, Object> requestMap = new HashMap<>();
            Map<String, Object> params = new HashMap<>();
            requestMap.put("request", param);
            params.put("c_request",requestMap);
            //params.put("operationID", ConstantEnum.HIS_ORDERS_REVIEW_10058.getKey());
            params.put("operationID", ConstantEnum.HIS_ORDERS_REVIEW_10058.getKey());
            System.out.println(JSON.toJSONString(params));
            JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, params);
            if(jsonObject.isEmpty()){
                return ResultGenerator.genFailedResult("医嘱复核失败");
            }
            log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
            if (null != jsonObject) {
                Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                if (resInt < 0) {
                    return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                }
            }

            Timestamp checkTime = new Timestamp(date.getTime());
            List<PatientOrdersEntity> patientOrdersEntityList = new CopyOnWriteArrayList<>();
            List<OrderOperationLogEntity> orderOperationLogEntityList = new CopyOnWriteArrayList<>();
            //更新医嘱表
            for(OrdersReviewDTO ordersReviewDTO:ordersReviewDTOList){
                //更新医嘱状态
                PatientOrdersEntity patientOrdersInfo = new PatientOrdersEntity();
                patientOrdersInfo.setExecStatusHis("2");
                patientOrdersInfo.setInpatorderdataId(ordersReviewDTO.getInpatorderdataId());
                patientOrdersInfo.setCheckDate(checkTime);
                //存放person_id
                patientOrdersInfo.setCheckNursePersonId(ordersReviewDTO.getPersonId());
                patientOrdersEntityList.add(patientOrdersInfo);
                //实例化对象
                Date startDate=null;
                Date releaseDate=null;
                try {
                    if(StringUtils.isNotBlank(ordersReviewDTO.getStartDate()) && ordersReviewDTO.getStartDate().length()>=16){
                        startDate = DateUtils.parseDate(ordersReviewDTO.getStartDate().substring(0,16)+":00","yyyy-MM-dd HH:mm:ss");
                    }
                    if(StringUtils.isNotBlank(ordersReviewDTO.getReleaseDate()) && ordersReviewDTO.getReleaseDate().length()>=16){
                        releaseDate =DateUtils.parseDate(ordersReviewDTO.getReleaseDate().substring(0,16)+":00","yyyy-MM-dd HH:mm:ss");
                    }

                } catch (ParseException e) {
                    e.printStackTrace();
                }
                OrderOperationLogEntity orderOperationLogEntity = new OrderOperationLogEntity(UUIDUtil.randomString(),null,ordersReviewDTO.getInpatNum(),null,patientOrdersInfo.getInpatorderdataId(),
                        date,6,ordersReviewDTO.getPersonId(),startDate,releaseDate);
                orderOperationLogEntity.initAdd();
                orderOperationLogEntityList.add(orderOperationLogEntity);
            }
            //修改医嘱加日志
            if(!CollectionUtils.isEmpty(patientOrdersEntityList)){
                orderMapper.updateBatchPatientOrderByIds(patientOrdersEntityList);
            }
            //添加日志
            if(!CollectionUtils.isEmpty(orderOperationLogEntityList)){
                orderMapper.insertOrderOperationLog(orderOperationLogEntityList);
            }
            return ResultGenerator.genOkResult();
        }else{
            return ResultGenerator.genOkResult();
        }
    }

    private static String fetchGroupKey(OrdersReviewDTO ordersReviewDTO){
        return ordersReviewDTO.getInpatNum()+"#"+ordersReviewDTO.getOrderNo();
    }

    public Result notReviewPatientList(String wardDeptId,String status){
        return ResultGenerator.genOkResult(orderMapper.notReviewPatientList(wardDeptId,status,null));
    }

    @Override
    public PageInfo<OrderInfoByInpatNoVo> queryPagesListApp(OrderPageDto orderPageDto) {
        PageHelper.startPage(orderPageDto.getPageNum(), orderPageDto.getPageSize());
        List<OrderListAppDto> list = this.orderMapper.queryOrderListApp(orderPageDto);
        list.stream().forEach(order -> {
            order.setList(this.orderMapper.selectOrdersByInpatAndOrderNo(order.getInpatNum(),order.getOrderNo()));
            //临时医嘱的状态需要根据医嘱单是否签名显示
            if ("临时医嘱".equals(order.getOrderStatus())) {
                Result result = nurseService.print("2", order.getInpatNum(), order.getInpatorderdataId());
                if (HttpStatus.OK.value() == result.getCode()) {
                    JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(result.getData()));
                    JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                    JSONArray jsonArray2 = JSONArray.parseArray(JSON.toJSONString(jsonObject.get("orderList")));
                    JSONObject jsonObject2 = (JSONObject) jsonArray2.get(0);
                    if (StringUtils.isNotBlank(jsonObject2.getString("executionSign")) && StringUtils.isNotBlank(jsonObject2.getString("executionTime"))) {
                        order.setStatus("已执行");
                    } else {
                        order.setStatus("未执行");
                    }
                }
            }
            String freqData = "";
            if (StringUtils.isNotEmpty(order.getCronDescriber())) {
                String hisExecTime = CronUtil.hisConverter(JSONObject.parseObject(order.getCronDescriber(), CronDescriber.class));
                order.setFreqData(hisExecTime);
            }
            /*List<String> freqs = orderMapper.queryFreqData(order.getInpatorderdataId());
            for(String freqItem : freqs){
                if(StringUtils.isNotBlank(freqItem)){
                    freqData += freqItem +"时 ";
                }
            }
            if(freqData.length()>0){
                freqData = freqData.substring(0,freqData.length()-1);
                if(StringUtils.isNotBlank(order.getFreqName())){
                    order.setFreqData(order.getFreqName()+ " " + freqData);
                }else{
                    order.setFreqData(freqData);
                }
            }else{
                if(StringUtils.isBlank(order.getFreqData())){
                    order.setFreqData("");
                }
            }*/
        });
        return new PageInfo(list);
    }

    /**
     * 格式化 医嘱信息
     *
     * @param orderInfoVo 医嘱
     */
    private void formatOrderVo(OrderInfoByInpatNoVo orderInfoVo) {
        // 设置医嘱执行状态
        checkExecStatus(orderInfoVo);
        //格式化相关信息
        if (orderInfoVo.getPlanEndDatetime() == null) {
            //没有停止时间就没有停止医生
            orderInfoVo.setStopUserName(StringUtils.EMPTY);
        }

        if (StringUtils.isBlank(orderInfoVo.getExecDatetime())) {
            // 没有执行时间就没有执行医生
            orderInfoVo.setExecUserName(StringUtils.EMPTY);
        }
        // 长期医嘱没有执行时间，也没有执行医生
        if (OrderTypeEnum.LONGTERM.getValue().equals(orderInfoVo.getOrderStatusValue())) {
            orderInfoVo.setExecDatetime(StringUtils.EMPTY);
            orderInfoVo.setExecUserName(StringUtils.EMPTY);
        }
        // 临时医嘱有执行时间，如果为空那么取节点的时间
        if (OrderTypeEnum.TEMPORARY.getValue().equals(orderInfoVo.getOrderStatusValue())) {
            if (StringUtils.isBlank(orderInfoVo.getExecDatetime())) {
                // 查询执行时间
                List<OrderTaskInfo> orderTaskInfoList = this.orderMapper.queryOrderTaskKey(orderInfoVo.getInpatorderdataId());
                if (CollectionUtils.isEmpty(orderTaskInfoList)) {
                    orderInfoVo.setExecDatetime(StringUtils.EMPTY);
                } else {
                    if(orderTaskInfoList.get(0).getEndDateTime()!=null){
                        orderInfoVo.setExecDatetime(DateFormatUtils.format(orderTaskInfoList.get(0).getEndDateTime(), "yyyy-MM-dd HH:mm"));
                    }else {
                        orderInfoVo.setExecDatetime(StringUtils.EMPTY);
                    }
                }
            }
        }
        // 复制主节点
        OrderInfoByInpatNoVo copyOrderVo = new OrderInfoByInpatNoVo();
        BeanUtils.copyProperties(orderInfoVo, copyOrderVo);
        orderInfoVo.setOrderInfoByInpatNoVoList(new ArrayList<>());
        orderInfoVo.getOrderInfoByInpatNoVoList().add(copyOrderVo);
        // 如果是药品才有子医嘱
        if ("药品".equals(orderInfoVo.getType())) {
            // 查询子节点
            List<OrderInfoByInpatNoVo> subOrderList = this.orderMapper.querySubOrderList(orderInfoVo.getInpatNum(), orderInfoVo.getOrderNo());
            orderInfoVo.getOrderInfoByInpatNoVoList().addAll(subOrderList);
        }
    }


    /**
     * 设置医嘱执行状态
     *
     * @param orderVo
     */
    private void checkExecStatus(OrderInfoByInpatNoVo orderVo) {
        // 结束时间不为空,并且是长期医嘱
        if (orderVo.getPlanEndDatetime() != null && OrderTypeEnum.LONGTERM.getValue().equals(orderVo.getOrderStatusValue())) {
            Date endDate = new Date(orderVo.getPlanEndDatetime().getTime());
            // 结束时间小于当前时间
            if (endDate.getTime() - System.currentTimeMillis() <= 0) {
                if (OrderTypeEnum.LONGTERM.getValue().equals(orderVo.getOrderStatusValue())) {
                    orderVo.setStatus(OrderExecStatusEnum.STOP.getName());
                    orderVo.setStatusId(OrderExecStatusEnum.STOP.getValue());
                    return;
                }
            }
        }
        // 临时医嘱 默认先给个执行中状态
//		if (OrderTypeEnum.TEMPORARY.getValue().equals(orderVo.getOrderStatusValue())) {
//			orderVo.setStatus(OrderExecStatusEnum.LOADING.getName());
//			orderVo.setStatusId(OrderExecStatusEnum.LOADING.getValue());
//		}
        // 已执行 只有临时医嘱有已执行
        if (OrderTypeEnum.TEMPORARY.getValue().equals(orderVo.getOrderStatusValue()) && orderVo.getUnFinishCount().intValue() == 0) {
            orderVo.setStatus(OrderExecStatusEnum.LOADED.getName());
            orderVo.setStatusId(OrderExecStatusEnum.LOADED.getValue());
            return;
        }
        // 长期医嘱 执行中
        if (OrderTypeEnum.LONGTERM.getValue().equals(orderVo.getOrderStatusValue()) && orderVo.getFinishCount().intValue() > 0 && orderVo.getUnFinishCount().intValue() != 0) {
            orderVo.setStatus(OrderExecStatusEnum.LOADING.getName());
            orderVo.setStatusId(OrderExecStatusEnum.LOADING.getValue());
            return;
        }
        // 临时医嘱 执行中
        if (OrderTypeEnum.TEMPORARY.getValue().equals(orderVo.getOrderStatusValue()) && orderVo.getAllCount().intValue() - orderVo.getUnFinishCount().intValue() > 0 && orderVo.getUnFinishCount().intValue() != 0) {
            orderVo.setStatus(OrderExecStatusEnum.LOADING.getName());
            orderVo.setStatusId(OrderExecStatusEnum.LOADING.getValue());
            return;
        }
        // 未执行 长期医嘱
        if (OrderTypeEnum.LONGTERM.getValue().equals(orderVo.getOrderStatusValue()) && orderVo.getFinishCount().equals(0)) {
            orderVo.setStatus(OrderExecStatusEnum.UNLOAD.getName());
            orderVo.setStatusId(OrderExecStatusEnum.UNLOAD.getValue());
            return;
        }
        // 未执行 临时医嘱
        if (OrderTypeEnum.TEMPORARY.getValue().equals(orderVo.getOrderStatusValue())
                && orderVo.getFinishCount().equals(0)
                && orderVo.getAllCount().equals(orderVo.getUnFinishCount())) {
            orderVo.setStatus(OrderExecStatusEnum.UNLOAD.getName());
            orderVo.setStatusId(OrderExecStatusEnum.UNLOAD.getValue());
            return;
        }


    }


    /*private static Integer comparingByBedNo(Map<String, Object> map){
        return Integer.parseInt(String.valueOf(map.get("bedNo")));
    }
    private static String comparingByCheckDate(Map<String, Object> map){
        return String.valueOf(map.get("createTime"));
    }
    private static Integer comparingByOrderSubNo(Map<String, Object> map){
        return Integer.parseInt(String.valueOf(map.get("orderSubNo")));
    }
    private static String comparingByOrderNo(Map<String, Object> map){
        return String.valueOf(map.get("orderNo"));
    }*/
    private static String comparingByCheckDate(OrderRevieInfoDetailByInpatVo map){
        return map.getPlanBeginDatetime();
    }
    private static Integer comparingByOrderSubNo(OrderRevieInfoDetailByInpatVo map){
        return Integer.parseInt(map.getOrderSubNo());
    }
    private static String comparingByOrderNo(OrderRevieInfoDetailByInpatVo map){
        return map.getOrderNo();
    }



    /**
     * 医嘱核对列表
     * @param inpatList
     * @param startDatetime
     * @param endDateTime
     * @param orderType  0 全部、1长期医嘱、2临时医嘱
     * @param status  0未核对 1已核对
     * @return
     */
    public Result ordersCheckList(String inpatList, String startDatetime, String endDateTime,String orderType,String status){
        if(StringUtils.isNotBlank(inpatList)){
            if("0".equals(status)){
                //未复核
                List<OrderReviewInfoByInpatVo> list = orderMapper.ordersCheckList(inpatList.split(","), startDatetime, endDateTime, orderType);
                if(!CollectionUtils.isEmpty(list)){
                    list.stream().forEach(orderReviewInfoByInpatVo->{
                        List<OrderRevieInfoDetailByInpatVo> children = orderReviewInfoByInpatVo.getChildren();
                        List<OrderRevieInfoDetailByInpatVo> childrenTemp = new ArrayList<>();

                        if(!CollectionUtils.isEmpty(children)){
                            children.stream().forEach(map->{
                                //获取执行时间
                                if (StringUtils.isNotEmpty(map.getCronDescriber())) {
                                    String hisExecTime = CronUtil.hisConverter(JSONObject.parseObject(map.getCronDescriber(), CronDescriber.class));
                                    map.setFreqTimes(hisExecTime);
                                }
                                //1 新增医嘱复核完成（新增医嘱未核对）   2 停止医嘱复核完成（新增医嘱已核对，停止医嘱未核对）   3 停止医嘱复核完成（新增医嘱未核对，停止医嘱未核对）
                                String flag = map.getFlag();

                                if(StringUtils.isNotBlank(flag) && ("1".equals(flag) || "2".equals(flag) || "3".equals(flag) || "4".equals(flag))){
                                    if(StringUtils.isNotBlank(map.getPlanBeginDatetime())){
                                        map.setPlanBeginDate(map.getPlanBeginDatetime().substring(0,16));
                                    }
                                    if(StringUtils.isNotBlank(map.getReleaseTime())){
                                        map.setReleaseDate(map.getReleaseTime().substring(0,16));
                                    }
                                    if("3".equals(flag)){
                                        map.setCheckFlag("1");
                                    }
                                    childrenTemp.add(map);
                                }
                                //长期医嘱并且exec_status_his=3,结束时间不为空
                                if(StringUtils.isNotBlank(flag) && "3".equals(flag)){
                                    OrderRevieInfoDetailByInpatVo stopMap = new OrderRevieInfoDetailByInpatVo();
                                    BeanUtils.copyProperties(map,stopMap);
                                    //起始时间
                                    stopMap.setPlanBeginDatetime(StringUtils.isNotBlank(stopMap.getEndTime())?stopMap.getEndTime():stopMap.getBeginTime());
                                    stopMap.setOrdersItem("停 "+stopMap.getOrdersItem());
                                    //下达时间
                                    stopMap.setReleaseTime(StringUtils.isNotBlank(stopMap.getStopTime())?stopMap.getStopTime():stopMap.getEndTime());
                                    stopMap.setOrderNo(stopMap.getOrderNo()+".1");
                                    if(StringUtils.isNotBlank(stopMap.getPlanBeginDatetime())){
                                        stopMap.setPlanBeginDate(stopMap.getPlanBeginDatetime().substring(0,16));
                                    }
                                    if(StringUtils.isNotBlank(stopMap.getReleaseTime())){
                                        stopMap.setReleaseDate(stopMap.getReleaseTime().substring(0,16));
                                    }
                                    if("3".equals(flag)){
                                        stopMap.setCheckFlag("2");
                                    }
                                    childrenTemp.add(stopMap);
                                }
                            });
                            //排序 按照床号先排序，然后按照审核时间进行排序，按照orderSubNo进行排序
                            List<OrderRevieInfoDetailByInpatVo> collect = new ArrayList<>();
                            if(!CollectionUtils.isEmpty(childrenTemp)){
                                collect = childrenTemp.stream().sorted(Comparator.comparing(OrderRevieInfoDetailByInpatVo::getOrderType).thenComparing(OrderRevieInfoDetailByInpatVo::getPlanBeginDatetime).thenComparingInt(OrderRevieInfoDetailByInpatVo::getSort).thenComparing(OrderRevieInfoDetailByInpatVo::getAdministration, Comparator.nullsLast(String::compareTo))
                                        .thenComparing(OrderRevieInfoDetailByInpatVo::getOrderNo).thenComparing(OrderRevieInfoDetailByInpatVo::getOrderSubNo).thenComparing(OrderRevieInfoDetailByInpatVo::getOrdersItem))
                                        .collect(Collectors.toList());
                            }
                            orderReviewInfoByInpatVo.setChildren(collect);
                        }
                    });

                    //判断
                    List<OrderReviewInfoByInpatVo> listCopy = new ArrayList<>();
                    list.stream().forEach(orderReviewInfoByInpatVo->{
                        if(!CollectionUtils.isEmpty(orderReviewInfoByInpatVo.getChildren())){
                            listCopy.add(orderReviewInfoByInpatVo);
                        }
                    });

                    return ResultGenerator.genOkResult(listCopy);
                }
            }else if("1".equals(status)){
                //已复核
                List<OrderReviewInfoByInpatVo> list = orderMapper.ordersCheckedList(inpatList.split(","), startDatetime, endDateTime, orderType);
                if(!CollectionUtils.isEmpty(list)){
                    list.stream().forEach(orderReviewInfoByInpatVo->{
                        List<OrderRevieInfoDetailByInpatVo> children = orderReviewInfoByInpatVo.getChildren();
                        List<OrderRevieInfoDetailByInpatVo> childrenTemp = new ArrayList<>();

                        if(!CollectionUtils.isEmpty(children)){
                            children.stream().forEach(map->{
                                if (StringUtils.isNotEmpty(map.getCronDescriber())) {
                                    String hisExecTime = CronUtil.hisConverter(JSONObject.parseObject(map.getCronDescriber(), CronDescriber.class));
                                    map.setFreqTimes(hisExecTime);
                                }
                                //1 新增医嘱复核完成（新增医嘱未核对）   2 停止医嘱复核完成（新增医嘱已核对，停止医嘱未核对）   3 停止医嘱复核完成（新增医嘱未核对，停止医嘱未核对）
                                String flag = map.getFlag();

                                if(StringUtils.isNotBlank(flag) && ("1".equals(flag) || "2".equals(flag) || "3".equals(flag) || "4".equals(flag))){
                                    if(StringUtils.isNotBlank(map.getPlanBeginDatetime())){
                                        map.setPlanBeginDate(map.getPlanBeginDatetime().substring(0,16));
                                    }
                                    if(StringUtils.isNotBlank(map.getReleaseTime())){
                                        map.setReleaseDate(map.getReleaseTime().substring(0,16));
                                    }
                                    if(StringUtils.isNotBlank(startDatetime) && StringUtils.isNotBlank(endDateTime) && StringUtils.isNotBlank(map.getPlanBeginDatetime())
                                            && endDateTime.compareTo(map.getPlanBeginDatetime().substring(0,10))>=0 && map.getPlanBeginDatetime().substring(0,10).compareTo(startDatetime)>=0){
                                        childrenTemp.add(map);
                                    }else if(StringUtils.isBlank(startDatetime) && StringUtils.isBlank(endDateTime)){
                                        childrenTemp.add(map);
                                    }
                                }
                                //长期医嘱并且exec_status_his=3,结束时间不为空
                                if(StringUtils.isNotBlank(flag) && "3".equals(flag)){
                                    OrderRevieInfoDetailByInpatVo stopMap = new OrderRevieInfoDetailByInpatVo();
                                    BeanUtils.copyProperties(map,stopMap);
                                    //起始时间
                                    stopMap.setPlanBeginDatetime(StringUtils.isNotBlank(stopMap.getEndTime())?stopMap.getEndTime():stopMap.getBeginTime());
                                    stopMap.setOrdersItem("停 "+stopMap.getOrdersItem());
                                    //下达时间
                                    stopMap.setReleaseTime(StringUtils.isNotBlank(stopMap.getStopTime())?stopMap.getStopTime():stopMap.getEndTime());
                                    stopMap.setOrderNo(stopMap.getOrderNo()+".1");
                                    if(StringUtils.isNotBlank(stopMap.getPlanBeginDatetime())){
                                        stopMap.setPlanBeginDate(stopMap.getPlanBeginDatetime().substring(0,16));
                                    }
                                    if(StringUtils.isNotBlank(stopMap.getReleaseTime())){
                                        stopMap.setReleaseDate(stopMap.getReleaseTime().substring(0,16));
                                    }
                                    stopMap.setCheckDate(stopMap.getStopCheckDate());
                                    stopMap.setCheckPersonName(stopMap.getStopCheckPersonName());

                                    if(StringUtils.isNotBlank(startDatetime) && StringUtils.isNotBlank(endDateTime) && StringUtils.isNotBlank(stopMap.getPlanBeginDatetime())
                                            && endDateTime.compareTo(stopMap.getPlanBeginDatetime().substring(0,10))>=0 && stopMap.getPlanBeginDatetime().substring(0,10).compareTo(startDatetime)>=0){
                                        childrenTemp.add(stopMap);
                                    }else if(StringUtils.isBlank(startDatetime) && StringUtils.isBlank(endDateTime)){
                                        childrenTemp.add(stopMap);
                                    }
                                }
                            });
                            //排序 按照床号先排序，然后按照审核时间进行排序，按照orderSubNo进行排序
                            List<OrderRevieInfoDetailByInpatVo> collect = new ArrayList<>();
                            if(!CollectionUtils.isEmpty(childrenTemp)){
                                collect = childrenTemp.stream().sorted(Comparator.comparing(OrderRevieInfoDetailByInpatVo::getOrderType).thenComparing(OrderRevieInfoDetailByInpatVo::getPlanBeginDatetime).thenComparingInt(OrderRevieInfoDetailByInpatVo::getSort).thenComparing(OrderRevieInfoDetailByInpatVo::getAdministration, Comparator.nullsLast(String::compareTo))
                                        .thenComparing(OrderRevieInfoDetailByInpatVo::getOrderNo).thenComparing(OrderRevieInfoDetailByInpatVo::getOrderSubNo).thenComparing(OrderRevieInfoDetailByInpatVo::getOrdersItem))
                                        .collect(Collectors.toList());
                            }
                            orderReviewInfoByInpatVo.setChildren(collect);
                        }
                    });

                    //判断
                    List<OrderReviewInfoByInpatVo> listCopy = new ArrayList<>();
                    list.stream().forEach(orderReviewInfoByInpatVo->{
                        if(!CollectionUtils.isEmpty(orderReviewInfoByInpatVo.getChildren())){
                            listCopy.add(orderReviewInfoByInpatVo);
                        }
                    });

                    return ResultGenerator.genOkResult(listCopy);
                }
            }
        }
        return ResultGenerator.genOkResult(null);
    }

    private static String fetchOrdersCheckGroup(OrdersReviewDTO ordersReviewDTO){
        return ordersReviewDTO.getCheckFlag()+"#"+ordersReviewDTO.getPersonId();
    }

    /**
     * 医嘱核对保存
     * @param inpatorderdataIds
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Result saveOrdersCheck(List<OrdersReviewDTO> inpatorderdataIds){
        //1 新增医嘱复核完成（新增医嘱未核对）   2 停止医嘱复核完成（新增医嘱已核对，停止医嘱未核对）   3 停止医嘱复核完成（新增医嘱未核对，停止医嘱未核对）
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");

        //去重复
        //List<OrdersReviewDTO> collect = inpatorderdataIds.stream().collect(Collectors.collectingAndThen(
        //        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(OrdersReviewDTO::getInpatorderdataId))), ArrayList::new));
        //获取系统时间
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        List<PatientOrdersEntity> ordersEntities = new ArrayList<>();
        if(!CollectionUtils.isEmpty(inpatorderdataIds)){
            //根据personId和checkFlag进行分组
            Map<String, List<OrdersReviewDTO>> collect = inpatorderdataIds.stream().collect(Collectors.groupingBy(e -> fetchOrdersCheckGroup(e)));
            if(collect!=null) {
                for (String key : collect.keySet()) {
                    PatientOrdersEntity patientOrdersEntity = new PatientOrdersEntity();
                    List<PatientOrderCheckLogEntity> patientOrderCheckLogEntityList=new ArrayList<>();
                    String[] flagAndPersonId = key.split("#");
                    if(flagAndPersonId!=null && flagAndPersonId.length==2) {
                        String flag = flagAndPersonId[0];
                        String personId = flagAndPersonId[1];
                        if ("1".equals(flag)) {
                            patientOrdersEntity.setCreateCheckDatetime(currentTime);
                            patientOrdersEntity.setCreateCheckPersonId(personId);
                        } else if ("2".equals(flag)) {
                            patientOrdersEntity.setStopCheckDatetime(currentTime);
                            patientOrdersEntity.setStopCheckPersonId(personId);
                        } else if ("4".equals(flag)) {
                            patientOrdersEntity.setCancelCheckDatatime(currentTime);
                            patientOrdersEntity.setCancelCheckPersonId(personId);
                        }
                        String inpatorderdataId = "";
                        for (OrdersReviewDTO ordersReviewDTO : collect.get(key)) {
                            inpatorderdataId += ordersReviewDTO.getInpatorderdataId() + ",";
                            PatientOrderCheckLogEntity patientOrderCheckLogEntity = new PatientOrderCheckLogEntity(UUIDUtil.randomString(), ordersReviewDTO.getInpatorderdataId(), flag, currentTime, personId);
                            patientOrderCheckLogEntity.initAdd();
                            patientOrderCheckLogEntityList.add(patientOrderCheckLogEntity);
                        }
                        if (StringUtils.isNotBlank(inpatorderdataId)) {
                            inpatorderdataId = inpatorderdataId.substring(0, inpatorderdataId.length() - 1);
                            patientOrdersEntity.setInpatorderdataId(inpatorderdataId);
                            String allId[] = patientOrdersEntity.getInpatorderdataId().split(",");
                            if(allId!=null && allId.length>0){
                                List allIdList = new CopyOnWriteArrayList(Arrays.asList(allId));
                                int listSize1=allIdList.size();
                                int listSize2=patientOrderCheckLogEntityList.size();
                                int toIndex1 = 500;
                                int toIndex2 = 500;
                                for (int i = 0; i < allIdList.size(); i += 500) {
                                    if (i + 500 > listSize1) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                                        toIndex1 = listSize1 - i;
                                    }
                                    List newList = allIdList.subList(i, i + toIndex1);
                                    PatientOrdersEntity newPatientOrdersEntity = new PatientOrdersEntity();
                                    BeanUtils.copyProperties(patientOrdersEntity,newPatientOrdersEntity);
                                    newPatientOrdersEntity.setInpatorderdataId(StringUtils.join(newList,","));
                                    orderMapper.updatePatientOrdersByInpatorderdataId(newPatientOrdersEntity);
                                }

                                for (int j = 0; j < patientOrderCheckLogEntityList.size(); j += 500) {
                                    if (j + 500 > listSize2) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                                        toIndex2 = listSize2 - j;
                                    }
                                    List newList = patientOrderCheckLogEntityList.subList(j, j + toIndex2);
                                    orderMapper.insertPatientOrderCheckLogEntityList(newList);
                                }
                            }


                        }
                    }
                }
            }
            return ResultGenerator.genOkResult("医嘱核对成功");
        }else{
            return ResultGenerator.genFailedResult("未选择医嘱数据进行核对");
        }
    }

    /**
     * 医嘱核对列表
     * @param inpatList
     * @param orderType 0 整理医嘱、1长期医嘱、2临时医嘱
     * @param status 0总对医嘱 1查询医嘱
     * @return
     */
    public Result ordersGeneralCheckList(String inpatList,String orderType,String status){
        List<OrderReviewInfoByInpatVo> list = new ArrayList<OrderReviewInfoByInpatVo>();
        if(StringUtils.isNotBlank(inpatList)) {
            if ("0".equals(status)) {
                String dateTime = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
                list = orderMapper.ordersGeneralCheckList(inpatList.split(","), dateTime, orderType);
                if(!CollectionUtils.isEmpty(list)){
                    list.stream().forEach(orderReviewInfoByInpatVo->{
                        List<OrderRevieInfoDetailByInpatVo> children = orderReviewInfoByInpatVo.getChildren();
                        if(!CollectionUtils.isEmpty(children)){
                            children.stream().forEach(map-> {
                                //获取执行时间
                                if (StringUtils.isNotEmpty(map.getCronDescriber())) {
                                    String hisExecTime = CronUtil.hisConverter(JSONObject.parseObject(map.getCronDescriber(), CronDescriber.class));
                                    map.setFreqTimes(hisExecTime);
                                }
                            });
                        }
                    });
                }
            }else if("1".equals(status)){
                list = orderMapper.ordersGeneralCheckedList(inpatList.split(","),orderType);
            }
        }
        return ResultGenerator.genOkResult(list);
    }

    /**
     * 医嘱总对列表
     * @param inpatList
     * @param status 0总对医嘱 1查询医嘱
     * @return
     */
    public Result ordersGeneralCheckTypeCount(String inpatList,String status){
        String dateTime = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
        //List<Map<String,Object>> list = new ArrayList<>();
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(){{
            add(new HashMap<String, Object>(){{
                put("orderType", "0");
            }});
            add(new HashMap<String, Object>(){{
                put("orderType", "1");
            }});
            add(new HashMap<String, Object>(){{
                put("orderType", "2");
            }});
        }};
        //0 整理医嘱、1长期医嘱、2临时医嘱
        if(StringUtils.isNotBlank(inpatList)) {
            if ("0".equals(status)) {
                list.parallelStream().forEach(x->{
                    int count = orderMapper.ordersGeneralCheckListCount(inpatList.split(","), dateTime, x.get("orderType").toString());
                    x.put("count",count);
                });
            }
        }
        return ResultGenerator.genOkResult(list);
    }

    /**
     * 医嘱复核功能
     * @param generalCheckLogDTO
     * @return
     */
    public Result saveGeneralCheck(GeneralCheckLogDTO generalCheckLogDTO){
        String checkPerson = generalCheckLogDTO.getCheckPerson();
        if(StringUtils.isNotBlank(checkPerson)){
            if(StringUtils.isNotBlank(generalCheckLogDTO.getInpatNum())){
                String inpatNums[] = generalCheckLogDTO.getInpatNum().split(",");
                //获取系统时间
                Timestamp currentTime = new Timestamp(new Date().getTime());
                List<GeneralCheckLogEntity> generalCheckLogEntityList = new ArrayList<>();
                for(String inpatNum:inpatNums){
                    GeneralCheckLogEntity generalCheckLogEntity = new GeneralCheckLogEntity();
                    generalCheckLogEntity.setLogId(UUIDUtil.randomString());
                    generalCheckLogEntity.initAdd();
                    generalCheckLogEntity.setWardDeptId(generalCheckLogDTO.getWardDeptId());
                    generalCheckLogEntity.setInpatNum(inpatNum);
                    generalCheckLogEntity.setType(generalCheckLogDTO.getType());
                    generalCheckLogEntity.setCheckDatetime(currentTime);
                    generalCheckLogEntity.setCheckPerson(generalCheckLogDTO.getCheckPerson());
                    generalCheckLogEntityList.add(generalCheckLogEntity);
                }
                orderMapper.insertGeneralCheckLog(generalCheckLogEntityList);
                return ResultGenerator.genOkResult("医嘱总对成功");
            }
        }else{
            return ResultGenerator.genFailedResult("请选择总对人员!");
        }
        return ResultGenerator.genOkResult();
    }

    public Result useMedicationList(String inpatNum, Integer page, Integer pageSize,String keyWords,String type){
        //PageHelper.startPage(page, pageSize);
        int totalLength = 0;
        List<Map<String,Object>> useMedicationList=orderMapper.useMedicationList(inpatNum,type,keyWords);
        if(!CollectionUtils.isEmpty(useMedicationList)){
            useMedicationList.parallelStream().forEach(x->{
                if (StringUtils.isNotEmpty((String)x.get("cronDescriber"))) {
                    String hisExecTime = CronUtil.hisConverter(JSONObject.parseObject((String)x.get("cronDescriber"), CronDescriber.class));
                    x.put("freq_dec",hisExecTime);
                }
                x.put("type",x.get("type")!=null?x.get("type").toString().substring(0, 2):null);
                this.setValue(x);
                if(x.get("orderStatusValue")!=null && "0".equals(x.get("orderStatusValue"))) {
                    List<Map<String, Object>> list = orderMapper.inpRecByOrderId((String) x.get("orderId"), null);
                    if(!CollectionUtils.isEmpty(list)){
                        for(Map<String, Object> y:list){
                            if(y.get("prescNo")!=null){
                                /*x.put("orders_class","处");
                                x.put("orders_class_type","3");
                                x.put("totalUnitId",y.get("dispense_amount")+""+y.get("countUnit"));
                                x.put("days","1");
                                x.put("order_sub_no","1");
                                x.put("freq_dec","");
                                x.put("stop_datetime","");*/
                                x.put("deleteFlag","1");
                            }
                        }
                    }
                }
            });
            useMedicationList=useMedicationList.stream().filter(x->!"1".equals(x.get("deleteFlag"))).collect(Collectors.toList());
            //排序
            if (!CollectionUtils.isEmpty(useMedicationList)) {
                //排序
                totalLength = useMedicationList.size();

                if (page != 0 && pageSize != 0) {
                    useMedicationList = useMedicationList.stream().skip((page - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
                }
            }
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(useMedicationList);
        pageInfo.setTotal(totalLength);
        return ResultGenerator.genOkResult(pageInfo);

    }

    public void setValue(Map<String,Object> orderInfoByInpatNoVo){
        //临时医嘱
        if(orderInfoByInpatNoVo.get("orderStatusValue")!=null && "0".equals(orderInfoByInpatNoVo.get("orderStatusValue"))) {
            String hisExecDateTime = (String)orderInfoByInpatNoVo.get("execDatetime");
            if (orderInfoByInpatNoVo.get("type")!=null && orderInfoByInpatNoVo.get("type").toString().equals("药品")) {
                orderInfoByInpatNoVo.put("execDatetime",null);
                if("雾化单".equals(orderInfoByInpatNoVo.get("administrationType"))){
                    Map<String, String> map = orderMapper.selectAtomizationTime((String)orderInfoByInpatNoVo.get("orderId"),null);
                    if(map!=null) {
                        orderInfoByInpatNoVo.put("execDatetime",map.get("atomizationTime"));
                    }
                }else if("注射单".equals(orderInfoByInpatNoVo.get("administrationType"))){
                    if("皮内注射".equals(orderInfoByInpatNoVo.get("administrationType")) || "皮试".equals(orderInfoByInpatNoVo.get("administrationType"))){
                        Map<String, String> map = orderMapper.selectInjectionTime1((String)orderInfoByInpatNoVo.get("orderId"),null);
                        if(map!=null) {
                            orderInfoByInpatNoVo.put("execDatetime",map.get("injectionTime1"));
                        }
                    }else if("皮下注射".equals(orderInfoByInpatNoVo.get("administration")) || "皮下注射(胰岛素)".equals(orderInfoByInpatNoVo.get("administration"))|| "M".equals(orderInfoByInpatNoVo.get("administration"))){
                        Map<String, String> map = orderMapper.selectInjectionTime2((String)orderInfoByInpatNoVo.get("orderId"),null);
                        if(map!=null) {
                            orderInfoByInpatNoVo.put("execDatetime",map.get("injectionTime2"));
                        }
                    }else{
                        Map<String, String> map = orderMapper.selectInfusionTime((String)orderInfoByInpatNoVo.get("orderId"),null);
                        if(map!=null) {
                            orderInfoByInpatNoVo.put("execDatetime",map.get("infusionTime"));
                        }
                    }
                }else if("输液单".equals(orderInfoByInpatNoVo.get("administrationType"))){
                    Map<String, String> map = orderMapper.selectInfusionTime((String)orderInfoByInpatNoVo.get("orderId"),null);
                    if(map!=null) {
                        orderInfoByInpatNoVo.put("execDatetime",map.get("infusionTime"));
                    }
                }else if("服药单".equals(orderInfoByInpatNoVo.get("administrationType"))){
                    Map<String, String> map = orderMapper.selectTakeTime((String)orderInfoByInpatNoVo.get("orderId"));
                    if(map!=null) {
                        orderInfoByInpatNoVo.put("execDatetime",map.get("takeTime"));
                    }

                }else if("肠内营养".equals(orderInfoByInpatNoVo.get("administrationType"))){
                    Map<String, String> map = orderMapper.selectNutritionTime((String)orderInfoByInpatNoVo.get("orderId"),null);
                    if(map!=null) {
                        orderInfoByInpatNoVo.put("execDatetime",map.get("nutritionTime"));
                    }
                } else if("治疗单".equals(orderInfoByInpatNoVo.get("administrationType")) || "其他给药单".equals(orderInfoByInpatNoVo.get("administrationType"))){
                    orderInfoByInpatNoVo.put("execDatetime",hisExecDateTime);
                }
            }else{
                orderInfoByInpatNoVo.put("execDatetime",hisExecDateTime);
            }
            if(StringUtils.isNotBlank((String)orderInfoByInpatNoVo.get("signNurseDatetime"))){
                orderInfoByInpatNoVo.put("execDatetime",(String)orderInfoByInpatNoVo.get("signNurseDatetime"));
            }
            orderInfoByInpatNoVo.put("freq_dec",orderInfoByInpatNoVo.get("execDatetime"));
        }
    }


    @Override
    public Result inpRecByOrderId(String orderId,String prescNum) {
        return ResultGenerator.genOkResult(orderMapper.inpRecByOrderId(orderId,prescNum));
    }

    @Override
    public Result queryStaticList(String startDateTime, String endDateTime,String wardId) {
        List<Map<String, Object>> resultList = new CopyOnWriteArrayList<>();
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> staticMap = new HashMap<>();
        Map<String, Object> requestMap = new HashMap<>();
        staticMap.put("source", "3");
        staticMap.put("hospital_no", orderMapper.getHospAreaNo(userId));
        staticMap.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
        //staticMap.put("operator", "887");
        staticMap.put("operationdate", DateUtil.dateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
        staticMap.put("dt_from", startDateTime.replace("+"," "));
        staticMap.put("dt_to", endDateTime.replace("+"," "));
        requestMap.put("request", staticMap);
        params.put("c_request", requestMap);
        params.put("operationID", ConstantEnum.HZQUERY_10006.getKey());
        log.info("操作码:{}-{}", ConstantEnum.HZQUERY_10006.getKey(), JSONObject.toJSONString(params));
        JSONObject jsonObject = HttpClientUtil.sendPost(hisQueryUrl, params);
        log.info("操作码:{}-result-{}", ConstantEnum.HZQUERY_10006.getKey(), jsonObject.toJSONString());
        return ResultGenerator.genOkResult(((JSONObject)((JSONObject)jsonObject.get("c_response")).get("response")).get("orders"));
        /*Map<String, Object> cresponseMap = JSON.parseObject(jsonObject.getString("c_response"), new TypeReference<Map<String, Object>>() {});
        if(cresponseMap!=null && cresponseMap.get("response")!=null ){
            Map<String,Object> response = (Map<String,Object>)cresponseMap.get("response");
            List<Map<String, Object>> list = (List<Map<String, Object>>) response.get("orders");
            List<String> inpatNumList = mealListMapper.queryPatientByWardId(wardId);
            if(!CollectionUtils.isEmpty(list) && !CollectionUtils.isEmpty(inpatNumList)){
                list.stream().forEach(x->{
                    String backPharmacistName = orderMapper.queryByPersonCode((String)x.get("back_pharmacist"));
                    if(StringUtils.isNotBlank(backPharmacistName)){
                        x.put("back_pharmacist",backPharmacistName);
                    }
                    if(inpatNumList.contains(x.get("patient_id"))){
                        resultList.add(x);
                    }
                });
            }
        }*/
        //return ResultGenerator.genOkResult(resultList);

    }

    public Result queryOrderBookKeepingTotalCost(String inpatNum){
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        String personCode = patientInHospitalMapper.queryPersonCodeByUserId(userId);
        PageHelper.startPage(1,1);
        List<OrderInfoByInpatNoVo> list = orderMapper.queryOrdersBookKeeping(inpatNum);
        if(!CollectionUtils.isEmpty(list)){
            OrderInfoByInpatNoVo orderInfoByInpatNoVo = list.get(0);
            //循环对记账进行处理
            String primaryId = orderInfoByInpatNoVo.getPrimaryId();
            //调用his
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> requestMap = new HashMap<>();
            Map<String, Object> param = new HashMap<>();
            param.put("patient_id", orderInfoByInpatNoVo.getInpatNum().split("-")[0]);
            param.put("visit_id", Integer.parseInt(orderInfoByInpatNoVo.getInpatNum().split("-")[1]));
            param.put("operator", personCode);
            param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            param.put("primary_id", primaryId);
            requestMap.put("request", param);
            map.put("c_request", requestMap);
            map.put("operationID", ConstantEnum.HZQUERY_10016.getKey());
            log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map.toString());
            JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl, map);
            log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
            if (null != jsonObject) {
                Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                if (resInt > 0) {
                    if (jsonObject.getString("c_response") != null) {
                        Map<String, Object> cresponseMap = JSON.parseObject(jsonObject.getString("c_response"), new TypeReference<Map<String, Object>>() {});
                        Map<String, Object> response = (Map<String, Object>) cresponseMap.get("response");
                        if (response != null && response.get("total_costs") != null) {
                            String totalCosts = String.valueOf(response.get("total_costs"));
                            return ResultGenerator.genOkResult(totalCosts);
                        }
                    }
                }
            }
        }
        return ResultGenerator.genOkResult(0);
    }

    /**
     * 医嘱记账查询
     * @param inpatNum
     * @param type 0 全部医嘱，1 未收费医嘱，2 已收费医嘱
     * @return
     */
    public Result queryOrdersBookKeeping(String inpatNum, String type,Integer page,Integer pageSize){
        List<OrderInfoByInpatNoVo> list = new CopyOnWriteArrayList<>();
        List<OrderInfoByInpatNoVo> resultList = new CopyOnWriteArrayList<>();
        List<OrderInfoByInpatNoVo> lastList = new CopyOnWriteArrayList<>();
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        String personCode = patientInHospitalMapper.queryPersonCodeByUserId(userId);
        //调用his
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> requestMap = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("patient_id", inpatNum.split("-")[0]);
        param.put("visit_id", Integer.parseInt(inpatNum.split("-")[1]));
        param.put("operator", personCode);
        param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
        //查询类别：1未收费医嘱 2已收费医嘱 3全部医嘱
        String queryType=type;
        if("0".equals(type)){
            queryType="3";
        }
        param.put("query_type", queryType);
        requestMap.put("request", param);
        map.put("c_request", requestMap);
        map.put("operationID", ConstantEnum.HZQUERY_10023.getKey());
        log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map.toString());
        System.out.println(JSON.toJSONString(map));
        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl, map);
        log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
        if (null != jsonObject) {
            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
            if (resInt > 0) {
                if (jsonObject.getString("c_response") != null) {
                    Map<String, Object> cresponseMap = JSON.parseObject(jsonObject.getString("c_response"), new TypeReference<Map<String, Object>>() {
                    });
                    Map<String, Object> response = (Map<String, Object>) cresponseMap.get("response");
                    if (response != null && response.get("orderinfo") != null) {
                        List<Map<String, Object>> orderinfo = (List<Map<String, Object>>) response.get("orderinfo");
                        if (!CollectionUtils.isEmpty(orderinfo)) {
                            orderinfo.parallelStream().forEach(x->{
                                OrderInfoByInpatNoVo orderInfoByInpatNoVo = new OrderInfoByInpatNoVo();
                                orderInfoByInpatNoVo.setPrimaryId((String)x.get("primary_id"));
                                //是否已记账：1已记账 0未记账
                                String feeFlag="1";
                                if("1".equals(String.valueOf(x.get("fee_flag")))){
                                    feeFlag="2";
                                }else if("0".equals(String.valueOf(x.get("fee_flag")))){
                                    feeFlag="1";
                                }
                                String orderStatus="";
                                if("1".equals(String.valueOf(x.get("repeat_indicator")))){
                                    orderStatus="长";
                                }else if("0".equals(String.valueOf(x.get("repeat_indicator")))){
                                    orderStatus="临";
                                }
                                orderInfoByInpatNoVo.setBookKeeping(feeFlag);
                                orderInfoByInpatNoVo.setOrderStatus(orderStatus);
                                orderInfoByInpatNoVo.setType(orderMapper.selectClinicalProjects((String)x.get("order_class")));
                                orderInfoByInpatNoVo.setPlanBeginDatetime(new Timestamp((DateUtil.stringToDate((String)x.get("start_date_time"),"yyyy-MM-dd HH:mm:ss")).getTime()));
                                orderInfoByInpatNoVo.setStartTime((String)x.get("start_date_time"));
                                orderInfoByInpatNoVo.setOrdersItem((String)x.get("order_text"));
                                System.out.println(x.get("dosage"));
                                String dosage = String.valueOf(x.get("dosage"));
                                Double ddosage = null;
                                if(StringUtils.isNotBlank(dosage) && !"null".equals(dosage)){
                                    ddosage=Double.parseDouble(dosage);
                                }
                                orderInfoByInpatNoVo.setItemDosage(ddosage);
                                orderInfoByInpatNoVo.setUnitName((String)x.get("dosage_units"));
                                orderInfoByInpatNoVo.setAdministration((String)x.get("administration"));
                                orderInfoByInpatNoVo.setFreqName((String)x.get("frequency"));
                                orderInfoByInpatNoVo.setExecDatetime((String)x.get("perform_schedule"));
                                orderInfoByInpatNoVo.setPlanEndDatetime(new Timestamp((DateUtil.stringToDate((String)x.get("stop_date_time"),"yyyy-MM-dd HH:mm:ss")).getTime()));
                                orderInfoByInpatNoVo.setOrdersRemark((String)x.get("freq_detail"));
                                String billingAttr="";
                                if("0".equals(x.get("billing_attr"))){
                                    billingAttr="常规";
                                }else if("1".equals(x.get("repeat_indicator"))){
                                    billingAttr="自备";
                                }else if("3".equals(x.get("repeat_indicator"))){
                                    billingAttr="出院带药";
                                }else if("4".equals(x.get("repeat_indicator"))){
                                    billingAttr="处方";
                                }
                                orderInfoByInpatNoVo.setOrdersRemark(billingAttr);
                                orderInfoByInpatNoVo.setPreformResult((String)x.get("perform_result"));
                                orderInfoByInpatNoVo.setInpatNum(inpatNum);
                                orderInfoByInpatNoVo.setOrderNo(String.valueOf(x.get("order_no")));
                                orderInfoByInpatNoVo.setOrderSubNo(String.valueOf(x.get("order_sub_no")));

                                list.add(orderInfoByInpatNoVo);
                            });
                        }
                    }
                }
            }
        }

        int totalLength=0;

        //0 全部医嘱，1 未收费医嘱，2 已收费医嘱
        if(!CollectionUtils.isEmpty(list)){
            resultList = list.stream().sorted(Comparator.comparing(OrderInfoByInpatNoVo::getStartTime)
                    .thenComparing(OrderInfoByInpatNoVo::getOrderNo).thenComparing(OrderInfoByInpatNoVo::getOrderSubNo)).collect(Collectors.toList());
            //过滤状态
            totalLength = resultList.size();
            //排序


            if (page != 0 && pageSize != 0) {
                lastList = resultList.stream().skip((page - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
            }
        }
        PageInfo<OrderInfoByInpatNoVo> pageInfo = new PageInfo<>(lastList);
        pageInfo.setTotal(totalLength);
        return ResultGenerator.genOkResult(pageInfo);
    }

    /**
     * 补划价
     */

    public Result ordersSupplement(List<OrdersReviewDTO> inpatorderdataIds){
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        String inpatNum = "";
        List<Map<String,String>> list = new CopyOnWriteArrayList<>();
        if(!CollectionUtils.isEmpty(inpatorderdataIds)){
            inpatNum=inpatorderdataIds.get(0).getInpatNum();
            inpatorderdataIds.stream().forEach(x->{
                Map<String,String> map = new HashMap<>();
                map.put("primary_id",x.getPrimaryId());
                list.add(map);
            });
        }
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> requestMap = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("patient_id", inpatNum.split("-")[0]);
        param.put("visit_id", Integer.parseInt(inpatNum.split("-")[1]));
        param.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
        param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
        param.put("list", list);
        requestMap.put("request", param);
        map.put("c_request", requestMap);
        map.put("operationID", ConstantEnum.HZQUERY_10020.getKey());
        log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map.toString());
        System.out.println(JSON.toJSONString(map));
        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl, map);
        log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
        if (null != jsonObject) {
            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
            if (resInt < 0) {
                return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
            }
        }
        return ResultGenerator.genOkResult("补划价成功");
    }

    /**
     * 药品信息
     */
    public Result queryCostByOrderId(OrdersReviewDTO inpatorderdataIds){
        List<OrderCostInfoDTO> resultList = new CopyOnWriteArrayList<>();
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> requestMap = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("patient_id", inpatorderdataIds.getInpatNum().split("-")[0]);
        param.put("visit_id", Integer.parseInt(inpatorderdataIds.getInpatNum().split("-")[1]));
        param.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
        param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
        param.put("primary_id", inpatorderdataIds.getPrimaryId());
        requestMap.put("request", param);
        map.put("c_request", requestMap);
        map.put("operationID", ConstantEnum.HZQUERY_10016.getKey());
        log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map.toString());
        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl, map);
        log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
        if (null != jsonObject) {
            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
            if (resInt < 0) {
                return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
            } else {
                if (jsonObject.getString("c_response") != null) {
                    Map<String, Object> cresponseMap = JSON.parseObject(jsonObject.getString("c_response"), new TypeReference<Map<String, Object>>() {
                    });
                    Map<String, Object> response = (Map<String, Object>) cresponseMap.get("response");
                    if (response != null && response.get("billinfo") != null) {
                        List<Map<String, String>> list = (List<Map<String, String>>)response.get("billinfo");
                        if(!CollectionUtils.isEmpty(list)){
                            list.parallelStream().forEach(x->{
                                DecimalFormat df = new DecimalFormat("#.00");
                                OrderCostInfoDTO orderCostInfoDTO = new OrderCostInfoDTO();
                                orderCostInfoDTO.setType(x.get("class_name"));
                                if (StringUtils.isNotBlank(x.get("billing_date_time")) && x.get("billing_date_time").length() >= 16) {
                                    orderCostInfoDTO.setValuationDate(x.get("billing_date_time").substring(0, 16));
                                }
                                //orderCostInfoDTO.setValuationDate(x.get("billing_date_time"));
                                orderCostInfoDTO.setEntryName(x.get("item_name"));
                                orderCostInfoDTO.setSpecifications(x.get("item_spec"));
                                orderCostInfoDTO.setNumber(String.valueOf(x.get("amount")));
                                orderCostInfoDTO.setUnit(x.get("units"));
                                orderCostInfoDTO.setPrice(String.valueOf(x.get("price")));
                                orderCostInfoDTO.setAmount(String.valueOf(x.get("costs")));
                                orderCostInfoDTO.setValuator(x.get("user_name"));
                                orderCostInfoDTO.setDeptName(x.get("ordered_by"));
                                orderCostInfoDTO.setExecDeptName(x.get("performed_by"));
                                orderCostInfoDTO.setSource(x.get("data_origin"));
                                orderCostInfoDTO.setOrderId("");
                                resultList.add(orderCostInfoDTO);
                            });
                        }
                    }
                }
            }
        }
        return ResultGenerator.genOkResult(resultList);
    }
}
